﻿define(['ko', 'utils', 'config', 'router',
'repositories/repository.cabinet', 
//'repositories/repository.products',
'repositories/repository.productcategories'], 
function(ko, utils, config, router, repoCabinet, repoProductCategories) {
	
        var self = this;
        var cabinet = ko.observable();
        var productCategories = ko.observableArray();
        var selectedCategory = ko.observable();
        var getProductCategories = function(){
			repoProductCategories.getProductCategories({
				results : productCategories
			}).done(function() {
				console.log(productCategories());
			});
		};
		
		var onCategoryClicked = function(data, event){
			var categoryId = data.id();
			data.isSelected(true);
			selectedCategory(data);
			router.navigateTo(config.hashes.store + "/" + categoryId);
		};
	
		selectedCategory.subscribe(function(oldValue) {
			if(oldValue){
				oldValue.isSelected(false);
			}
		}, null, "beforeChange");
	
		var getCabinet = function(inParam) {
		repoCabinet.getCabinets({
			results : cabinet,
			param : inParam
		}).done(function() {
			//alert("code == "+cabinet()[0].code());
			console.log(cabinet());
		});
		};
		
		var loadData = function(routeData) {
			var self = this;
			getCabinet({code: routeData.id});
			getProductCategories();
		};
		
		var activate = function(routeData) {
			loadTemplate.call(this, routeData);
		};
		
		var loadTemplate = function(routeData) {	
			var self = this;
			
			utils.loadTemplate(config.viewIds.product_detail, "default/tmpl/" + config.viewTplNames.product_detail, function() {
			bind.call(self);
			});
			loadData(routeData);
		};
	
        var bind = function() {
			ko.applyBindings(this, $(config.viewIds.product_detail).get(0));
		};
	   
        return {
        	activate : activate,
            cabinet: cabinet,
            productCategories: productCategories,
            onCategoryClicked: onCategoryClicked,
            selectedCategory: selectedCategory
        };
 });